package com.zeta.auth.controller;

import com.wf.captcha.SpecCaptcha;
import com.zeta.auth.common.cachekey.CaptchaStringCacheKey;
import com.zeta.auth.model.vo.CaptchaResponseVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zetaframework.annotation.redis.Limit;
import org.zetaframework.base.result.ApiResult;
import org.zetaframework.controller.SuperBaseController;
import org.zetaframework.core.helper.EnvHelper;

/**
 * 验证码 前端控制器
 *
 * @author gcc
 */
@Tag(name = "验证码", description = "2.验证码")
@RequestMapping("/auth/captcha")
@RestController
@RequiredArgsConstructor
public class CaptchaController implements SuperBaseController {

    private final CaptchaStringCacheKey captchaCacheKey;
    private final EnvHelper envHelper;

    /**
     * 图形验证码
     */
    @SecurityRequirements
    @Limit(name = "验证码接口限流", count = 10, describe = "您的操作过于频繁，请稍后再试")
    @Operation(summary = "获取验证码")
    @GetMapping
    public ApiResult<CaptchaResponseVO> captcha() {
        long key = System.currentTimeMillis();

        // 验证码值缓存到redis, 5分钟有效(ps: 缓存有效时间请看CaptchaStringCacheKey#getExpire)
        SpecCaptcha specCaptcha = new SpecCaptcha(120, 40, 5);
        captchaCacheKey.set(key, specCaptcha.text());

        // 如果生产环境，不返回验证码的值
        return envHelper.isProdEnvironment()
                ? success(new CaptchaResponseVO(key, specCaptcha.toBase64()))
                : success(new CaptchaResponseVO(key, specCaptcha.toBase64(), specCaptcha.text()));
    }
}
